package engine.scene
{
	import engine.GameData;
	import engine.data.ModelLocator;
	import engine.data.RoleVo;
	import engine.data.SceneObject;
	import engine.display.TalkManage;
	import engine.event.CustomEvent;
	import engine.flag.GameDefine;
	import engine.flag.ObjType;
	import engine.flag.PlayerActionFlag;
	import engine.logic.walk.NpcIconManage;
	import engine.logic.walk.WalkLogic;
	import engine.logic.walk.WalkManager;
	import engine.net.event.CustomMsgEvent;
	import engine.net.messages.CustomToClientFlag;
	import engine.net.messages.CustomToServerFlag;
	import engine.net.mgr.SystemSender;
	import engine.newUi.FactionBossUI;
	import engine.newUi.SnowBossBloodUI;
	import engine.newUi.WorldBossBloodUI;
	import engine.pool.ObjectPool;
	import engine.scene.player.BasePlayerModel;
	import engine.scene.player.NpcModel;
	import engine.scene.player.PlayerModel;
	import engine.scene.player.RoleModel;
	import engine.tip.TipsMainLogic;
	
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.ui.Mouse;
	
	import newx.StageInfo;
	import newx.com.ResManager;
	import newx.com.config.StaticIni;
	import newx.utils.DateFormatter;
	import newx.utils.FilterUtil;
	
	public class ScenePlayerLogic
	{
		private var _model 			:ModelLocator;
		
		private var _isEnd				:Boolean;
		
		private var _playerDepts		:Array;
		
		private var _waits				:Array;
		
		private var _sceneClickLogic	:SceneClickLogic;
		
		private var _playerVisible		:Boolean = false;
		
		public static var  _playerMax			:int = 30;
		
		private var _pic:MovieClip 	= new MovieClip();
		private var makeSnowMc:MovieClip 	= new MovieClip();
		
		
		public function get playerVisible():Boolean
		{
			return _playerVisible;
		}
		
		public function get playerMax():int
		{
			return _playerMax;
		}
		
		public function set playerMax(value:int):void
		{
			_playerMax = value;
		}
		
		private function getFreeScenePlayer( obj : SceneObject ):BasePlayerModel
		{
			var modelClass : Class;
			if( obj is RoleVo )
			{
				modelClass = RoleModel;
			}else if( obj.Type == ObjType.Player )
			{
				modelClass = PlayerModel;
			}else
			{
				modelClass = NpcModel;;
			}
			return ObjectPool.GetPool( modelClass ).borrowObject() as BasePlayerModel;
		}
		
		public function ScenePlayerLogic()
		{
			_model 			= ModelLocator.getInstance();
			
			_sceneClickLogic= new SceneClickLogic();
			
			_playerDepts	= [];
			
			_waits			= [];
			
			_pic      		= ResManager.newResClass("CustomControl_0158") as MovieClip;
			_pic.visible    = false;
			makeSnowMc      		= ResManager.newResClass("CustomControl_085") as MovieClip;
			makeSnowMc.visible    = false;
			
			_playerMax		=	int(StaticIni.getIniVar("SceneMaxPlayer","num"));
		}
		
		/**
		 *	添加玩家 
		 * @param tObj
		 * 
		 */
		public function addNpc(tObj:SceneObject):void
		{
			var scenePlayer : BasePlayerModel = getScenePlayerByID( tObj.ObjID );
			var canVisible:Boolean = (tObj.GetPropertiesEx( "CantVisible" ) != 1);
			if( null == scenePlayer )
			{
				function setModelScale(valX:Number,valY:Number):void
				{
					scenePlayer.playerPlace.scaleX=valX
					scenePlayer.playerPlace.scaleY=valY;
					scenePlayer.setPlayerName();
				}
				
				if( tObj is RoleVo )
				{
					scenePlayer = GameData.Role;
					
					WalkLogic.Role = GameData.Role;
					
					scenePlayer.killMove();
				}else
				{
					scenePlayer = getFreeScenePlayer( tObj );
					if( tObj.Type!=ObjType.DragonNPC &&
						( (GameData.SceneType!=GameDefine.SceneType_WorldBossScene && GameData.SceneType!=GameDefine.SceneType_SnowBallFightScene) || !(scenePlayer is PlayerModel)
						))
					{
						addViewPointEvent( scenePlayer );
					}
				}
				
				scenePlayer.playerObj = tObj;
				
				if(!canVisible)return;
				scenePlayer.mouseChildren = scenePlayer.mouseEnabled = scenePlayer.visible = canVisible;
				
				if(!WorldBossBloodUI.getInstance().isHideBuffs || scenePlayer.playerObj.Type!=ObjType.HierogramNPC)
				{
					if( _playerDepts.length < _playerMax || tObj.Type != 1)
					{
						
						if(GameData.SceneType==GameDefine.SceneType_ForbiddenAreaScene)
						{
							setModelScale(0.5,0.5);
						}
//						else if(scenePlayer.playerObj.Type==ObjType.SnowDrift)
//						{
//							var scale:Number	=	(70 + 3*scenePlayer.playerObj.GetPropertiesEx("SnowBallCount"))*0.01;
//							setModelScale(scale,scale);
//						}
						else
						{
							setModelScale(1,1);
						}
						
						scenePlayer.LoadCompleteFun	= function():void
						{
//							scenePlayer.visible = _playerVisible;
//							scenePlayer.setVisible(_playerVisible);
							SceneManager.getInstance().norSceneView.playerBG.addChild( scenePlayer );
							_playerDepts.push( scenePlayer );
						}
						
					}else
					{
						scenePlayer.LoadCompleteFun	=	null;
						_waits.push( scenePlayer );
					}
				}
			}
//			else
//			{
//				scenePlayer.playerObj = tObj;
//			}
			NpcIconManage.getInstance().addNpcItems(scenePlayer,tObj.GetPropertiesEx("ConfigID"),tObj);
			if(tObj.Type	==	ObjType.Player)
			{
				TalkManage.getInstance().addPlay(scenePlayer,String(tObj.GetPropertiesEx("Name")),scenePlayer.width,scenePlayer.height,false,tObj);
			}else
			{
				TalkManage.getInstance().addNPC(scenePlayer,String(tObj.GetPropertiesEx("ConfigID")),scenePlayer.width,scenePlayer.height,false,tObj);
				TalkManage.getInstance().allshowNPCTalkContent();
			}
			
			
			
			if( null != scenePlayer && scenePlayer is PlayerModel && !( scenePlayer is RoleModel ) )
			{
				if(_waits.indexOf(scenePlayer) == -1)
				{
					scenePlayer.setVisible( _playerVisible );
				}
				else
				{
					scenePlayer.setVisible( false );
				}
				
			}
			
			if(GameData.SceneType == GameDefine.SceneType_WorldBossScene && scenePlayer.playerObj.CheckProperties("CreatorType") && scenePlayer.playerObj.GetPropertiesEx("CreatorType") == 3)
			{
				WorldBossBloodUI.getInstance().npcModel = scenePlayer;
				WorldBossBloodUI.getInstance().update();
			}
			if(GameData.SceneType == GameDefine.SceneType_FactionBossScene && scenePlayer.playerObj.CheckProperties("CreatorType") && scenePlayer.playerObj.GetPropertiesEx("CreatorType") == 4)
			{
				FactionBossUI.getInstance().npcModel = scenePlayer;
				FactionBossUI.getInstance().update();
			}
			if(GameData.SceneType == GameDefine.SceneType_SnowBallFightScene && scenePlayer.playerObj.CheckProperties("CreatorType") && scenePlayer.playerObj.GetPropertiesEx("CreatorType") == 5)
			{
				SnowBossBloodUI.getInstance().npcModel = scenePlayer;
				SnowBossBloodUI.getInstance().update();
			}
			scenePlayer.setPlayerName();
			_model.dispatchEvent( new CustomEvent( CustomEvent.ADD_NPC, [ scenePlayer ] ) );
		}
		
		public function removeNpcByObjId( objId : Point ):void
		{
			removeNpc( getScenePlayerByID( objId ) );
		}
		
		/**
		 *	删除玩家 
		 * @param obj
		 * 
		 */
		public function removeNpc(playerModel:BasePlayerModel):void
		{
			if( null != playerModel )
			{
				if(_playerDepts.indexOf( playerModel )!=-1)
				{
					_playerDepts.splice( _playerDepts.indexOf( playerModel ), 1 );
					if(SceneManager.getInstance().norSceneView.playerBG.contains(playerModel))
						SceneManager.getInstance().norSceneView.playerBG.removeChild(playerModel);
				}
				if(_waits.indexOf( playerModel )!=-1) 		
					_waits.splice( _waits.indexOf( playerModel ), 1 );
				
				ObjectPool.returnPool( playerModel );
				
				removeViewPointEvent( playerModel );
				TalkManage.getInstance().removePlay(playerModel.playerName);
				
				var showNum:int	=	SceneManager.getInstance().norSceneView.playerBG.numChildren;
				
				if( _waits.length > 0 && showNum < _playerMax )
				{
					var player:BasePlayerModel	=	_waits.pop();
//					player.visible				=	_playerVisible;
					player.setVisible(_playerVisible);
					if(_playerVisible)
					{
						SceneManager.getInstance().norSceneView.playerBG.addChild( player );
					}
					WalkManager.getInstance().walkLogic.changeDept();
				}
			}
		}
		
		public function changePlayerVisible(val:Boolean):void
		{
			_playerVisible = val;
			
			var playerBg : Sprite = SceneManager.getInstance().norSceneView.playerBG;
			
			var player : BasePlayerModel;
			
			for(var i:int; i < playerBg.numChildren ; i ++)
			{
				player = playerBg.getChildAt(i) as BasePlayerModel;
				
				if( null != player && player is PlayerModel && !( player is RoleModel ) )
				{
					player.setVisible( val );
				}
			}
		}
		
		/**
		 *	根据属性更新玩家信息 
		 */		
		public function updataSceneObjByProperty( npcObj : SceneObject, propertyName : String ):void
		{
			var npcModel : BasePlayerModel = getScenePlayerByID( npcObj.ObjID );
			
			if( null !=  npcModel )
			{
				switch( propertyName )
				{
					case "CantVisible":
					{
						npcModel.mouseChildren = npcModel.mouseEnabled = npcModel.visible = 
							npcObj.GetPropertiesEx( "CantVisible" ) != 1;
						break;
					}
					case "GameAFKStatus":
					{
						npcModel.status = npcObj.GetPropertiesEx( "GameAFKStatus" ) == 0 ? PlayerActionFlag.NormalWait : PlayerActionFlag.Sit;
						break;
					}
					case "HP":
					case "MaxHP":
					{
						( npcModel as NpcModel ).updataBoosHp( npcObj.GetPropertiesEx("HP"), npcObj.GetPropertiesEx("MaxHP"));
						break;
					}
					case "WorldPlayerDead":
					{
						( npcModel as PlayerModel ).worldPlayDead = ( npcObj.GetPropertiesEx("WorldPlayerDead") );
						break;
					}
					case "FollowPet":
					{	
						( npcModel as PlayerModel ).followPet =npcObj.GetPropertiesEx( "FollowPet" );
						break;
					}
					case "FollowPetName":
					{
						
						( npcModel as PlayerModel ).followPetName =npcObj.GetPropertiesEx( "FollowPetName");
						break;
					}
					case "FollowPetGrade":
					{
						
						( npcModel as PlayerModel ).followPetGrade =npcObj.GetPropertiesEx( "FollowPetGrade");
						break;
					}
					case "FollowPetLevel":
					{
						
						( npcModel as PlayerModel ).followPetLevel =npcObj.GetPropertiesEx( "FollowPetLevel");
						break;
					}	
					case "ModelEx":
					case "ClotheModel":
					case "Model":
					{
						( npcModel as PlayerModel ).upDataPlayModel(npcObj);
						break;
					}
					case "ChallengeIndex":
					{
						( npcModel as PlayerModel ).updataPlayerChange(npcObj);
						break;
					}
					case "GuildName":
					{
						( npcModel as BasePlayerModel ).setPlayerName(); 
						( npcModel as PlayerModel ).updataPlayerChange(npcObj);
						break;
					}
					case "SnowBallCount":
					{
						(npcModel as BasePlayerModel).playerMovie.scaleX = (npcModel as BasePlayerModel).playerMovie.scaleY = (70 + 3*npcObj.GetPropertiesEx("SnowBallCount"))*0.01;
					}
				}
			}
		}
		
		/**
		 * 获取场景上的坑位
		 * */
		public function getScenePlayerByID( objID:Point ):BasePlayerModel
		{
			for each(var scenePlayer : BasePlayerModel in _playerDepts )
			{
				if( scenePlayer.playerObj != null && objID.equals( scenePlayer.playerObj.ObjID ) )
				{
					return scenePlayer;
				}
			}
			
			return null;
		}
		/**
		 * 更据对象号获取 
		 * @param val
		 * @return 
		 * 
		 */		
		public function getScenePlayByConfigID(val:String):BasePlayerModel
		{
			for each(var scenePlayer : BasePlayerModel in _playerDepts )
			{
				if(scenePlayer.playerObj.CheckProperties("ConfigID"))
				{
					if( val  == scenePlayer.playerObj.GetProperties("ConfigID"))
					{
						return scenePlayer;
					}
				}
			}
			return null;
		}
		
		/**
		 *	改变舞台场景npc状态（任务npc） 
		 */
		public function changeNpcStage(npc : Array):void
		{
			var objId 		: Point			=	npc[0];
			
			var sceneNpc	: NpcModel	=	getScenePlayerByID( objId ) as NpcModel;
			//无效的站位点
			if( null == sceneNpc) return;
			sceneNpc.setStatusIcon( npc[ 1 ] );
			sceneNpc.updataPlayer(sceneNpc.npcObj);
		}
		
		/**清空场景对象*/
		public function clear():void
		{
			var length:int	=	_playerDepts.length;
			_waits = [];
			for(var i:int=0;i<length;i++)
			{
				removeNpc( _playerDepts[0] );
			}
			_playerDepts = [];
		}
		
		/**
		 *	玩家
		 */
		public function get playerDepts():Array
		{
			return _playerDepts.concat();;
		}
		
		/**
		 * 添加站位点事件,鼠标点击效果 
		 * @param pMc
		 * 
		 */		
		public function addViewPointEvent( scenePlayer : BasePlayerModel ):void
		{
			scenePlayer.buttonMode	=	true;
			scenePlayer.addEventListener(MouseEvent.MOUSE_DOWN,	onClick);
			scenePlayer.addEventListener(MouseEvent.MOUSE_OVER, onOver);
			scenePlayer.addEventListener(MouseEvent.MOUSE_MOVE, onMove);
			scenePlayer.addEventListener(MouseEvent.MOUSE_OUT, 	onOut);
		}
		
		/**
		 * 移除站位点事件 
		 * @param pMc
		 * 
		 */
		private function removeViewPointEvent( scenePlayer : BasePlayerModel ):void
		{
			scenePlayer.buttonMode	=	false;
			scenePlayer.removeEventListener(MouseEvent.MOUSE_DOWN,	onClick);
			scenePlayer.removeEventListener(MouseEvent.MOUSE_OVER, 	onOver);
			scenePlayer.removeEventListener(MouseEvent.MOUSE_MOVE, 	onMove);
			scenePlayer.removeEventListener(MouseEvent.MOUSE_OUT, 	onOut);
		}
		
		private function onOver(event:MouseEvent):void
		{
			event.currentTarget.filters = [ FilterUtil.WhiteGlowFilter ];
			(event.currentTarget as BasePlayerModel).removeEventListener(MouseEvent.MOUSE_OVER,onOver);
			//帮派仙宴
			if((event.currentTarget is NpcModel) && 
				(event.currentTarget as NpcModel).playerObj.Type	 ==	39 &&
				!_pic.stage)
			{
				SystemSender.getInstance().CustomMsg(
					CustomToServerFlag.CLIENT_CUSTOMMSG_GUILD_DINNER_NPC_TIPS);
				_model.addEventListener( String(CustomToClientFlag.SERVER_CUSTOMMSG_GUILD_DINNER), getDinnerTips );
				Mouse.hide();
				_pic.play();
				_pic.mouseEnabled	=	_pic.mouseChildren	=	false;
				StageInfo.stage.addChild(_pic);
				_pic.x = StageInfo.stage.mouseX - _pic.width;
				_pic.y = StageInfo.stage.mouseY - _pic.height;
				_pic.visible = true;
			}
			/*else if((event.currentTarget is NpcModel) && 
			(event.currentTarget as NpcModel).playerObj.Type	 ==	ObjType.SnowDrift &&
			!makeSnowMc.stage)
			{
			//				SystemSender.getInstance().CustomMsg(
			//					CustomToServerFlag.CLIENT_CUSTOMMSG_GUILD_DINNER_NPC_TIPS);
			//				_model.addEventListener( String(CustomToClientFlag.SERVER_CUSTOMMSG_GUILD_DINNER), getDinnerTips );
			Mouse.hide();
			makeSnowMc.mouseEnabled	=	makeSnowMc.mouseChildren	=	false;
			makeSnowMc.x = StageInfo.stage.mouseX - _pic.width;
			makeSnowMc.y = StageInfo.stage.mouseY - _pic.height;
			StageInfo.stage.addChild(makeSnowMc);
			makeSnowMc.visible = true;
			makeSnowMc.play();
			}*/
		}
		
		private function onOut(event:MouseEvent):void
		{
			event.currentTarget.filters = null;
			(event.currentTarget as BasePlayerModel).addEventListener(MouseEvent.MOUSE_OVER,onOver);
			
			if((event.currentTarget is NpcModel) && 
				(event.currentTarget as NpcModel).playerObj.Type	 ==	39)
			{
				Mouse.show();
				_pic.visible = false;
				_pic.stop();
				StageInfo.stage.removeChild(_pic);
				TipsMainLogic.instance.reSetPosition();
				TipsMainLogic.instance.hide();
				_model.removeEventListener( String(CustomToClientFlag.SERVER_CUSTOMMSG_GUILD_DINNER), getDinnerTips );
			}
			/*else if((event.currentTarget is NpcModel) && 
			(event.currentTarget as NpcModel).playerObj.Type	 ==	ObjType.SnowDrift)
			{
			Mouse.show();
			makeSnowMc.visible = false;
			makeSnowMc.stop();
			StageInfo.stage.removeChild(makeSnowMc);
			TipsMainLogic.instance.reSetPosition();
			TipsMainLogic.instance.hide();
			//				_model.removeEventListener( String(CustomToClientFlag.SERVER_CUSTOMMSG_GUILD_DINNER), getDinnerTips );
			}*/
		}
		
		private function onMove(e:MouseEvent):void
		{
			_pic.x = StageInfo.stage.mouseX;
			_pic.y = StageInfo.stage.mouseY;
			makeSnowMc.x = StageInfo.stage.mouseX;
			makeSnowMc.y = StageInfo.stage.mouseY;
			e.updateAfterEvent();
		}
		
		private function getDinnerTips(e:CustomMsgEvent):void
		{
			var serverArr:Array = e.pList;
			
			if(serverArr[0] == 5){
				var name:String = serverArr[1];
				var time:String = DateFormatter.SecondFormart(serverArr[2]);
				var isJoin:int  = int(serverArr[3]);
			}
			
			TipsMainLogic.instance.X_AWAY	=	80;
			//0:可参与 1:已经参加 2:不可参与
			switch(isJoin)
			{
				case 0:
					TipsMainLogic.instance.showString(StaticIni.getSwfLangStrVar("CocktailStr_14",
						[name, time, StaticIni.getSwfLangStr("CocktailStr_15")]));
					break;
				case 1:
					TipsMainLogic.instance.showString(StaticIni.getSwfLangStrVar("CocktailStr_14",
						[name, time, StaticIni.getSwfLangStr("CocktailStr_16")]));
					break;
				case 2:
					TipsMainLogic.instance.showString(StaticIni.getSwfLangStrVar("CocktailStr_14",
						[name, time, StaticIni.getSwfLangStr("CocktailStr_17")]));
					break;
				default:
					break;
			}
		}
		
		//点击舞台
		private function onClick(e:MouseEvent):void
		{
			e.stopImmediatePropagation();			
			_sceneClickLogic.sceneClick( GameData.Role, e.currentTarget as BasePlayerModel );
		}
		
		public function getNpcs():Array
		{
			var npcs : Array = [];
			for each( var npc : BasePlayerModel in _playerDepts )
			{
				if( npc is NpcModel )
				{
					npcs.push( npc );	
				}
			}
			return npcs;
		}
		
		public function hasNpc():Boolean
		{
			for each( var npc : BasePlayerModel in _playerDepts )
			{
				if( npc is RoleModel )
				{
					continue;
				}
				if( npc.visible )
				{
					return true;
				}
			}
			return false;
		}
	}
}